<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/24
 * Time: 9:30
 */

namespace app\api\controller;

class Openid
{
    protected $url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 获取openId
     * @param $code
     * @return string
     */
    public function getOpenid($code)
    {
        $appid = "wxde4599bcc831b168";

        $secret = "70051f077005008f56534be4cbea9367";

        $sql = sprintf($this->url,$appid,$secret,$code);

        $result = https_request($sql);

        $result = json_decode($result,true);

        if (isset($result["error"])) {
            exit ("出现错误");
        }

        if (isset($result["openid"])) {
            $openid = $result["openid"];
        }

        $token = md5(date("YmdHis",time()));

        \think\facade\Cache::set("token",$token);

        return json_encode(["code" => 1 , "message" => "成功" , "data" => $openid , "token" => $token]);
    }
}

//提交菜单内容给服务器
function https_request($url,$data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}